package org.example.model;

import org.example.observer.Observer;
import org.example.observer.EnvironmentData;
import org.example.state.MachineState;
import org.example.state.IdleState;
import org.example.strategy.PathPlanningContext;
import org.example.chain.SafetyData;
import org.example.facade.FarmSystemFacade;

public abstract class FarmMachine implements org.example.observer.Observer {
    protected String id;
    protected String type;
    protected MachineState state;
    protected double positionX;
    protected double positionY;
    protected double fuel;
    protected boolean isWorking;
    protected PathPlanningContext pathPlanningContext;

    public FarmMachine(String id) {
        this.id = id;
        this.state = new IdleState();
        this.positionX = 0.0;
        this.positionY = 0.0;
        this.fuel = 100.0;
        this.isWorking = false;
    }

    public abstract void performTask();

    @Override
    public void update(EnvironmentData data) {
        System.out.println(type + "[" + id + "] 接收到环境数据更新: " + data);

        if (data.isHasObstacle()) {
            System.out.println(type + "[" + id + "] 检测到障碍物，距离: " + data.getObstacleDistance() + "m");
            state.handleEvent(this, "检测到障碍物");

            SafetyData safetyData = new SafetyData();
            safetyData.setObstacleInfo("距离" + data.getObstacleDistance() + "m处有障碍物");
            safetyData.setObstacleAvoided(false);

            FarmSystemFacade facade = new FarmSystemFacade();
            facade.handleSafetyEvent(this, "检测到障碍物", safetyData);
        }

        if (data.getSoilMoisture() > 75) {
            System.out.println(type + "[" + id + "] 检测到高湿度土壤，调整路径规划");
            state.handleEvent(this, "土壤湿度过高");
        }
    }

    public String getId() { return id; }
    public String getType() { return type; }
    public MachineState getState() { return state; }
    public void setState(MachineState state) { this.state = state; }
    public double getPositionX() { return positionX; }
    public void setPositionX(double positionX) { this.positionX = positionX; }
    public double getPositionY() { return positionY; }
    public void setPositionY(double positionY) { this.positionY = positionY; }
    public double getFuel() { return fuel; }
    public void setFuel(double fuel) { this.fuel = fuel; }
    public boolean isWorking() { return isWorking; }
    public void setWorking(boolean working) { isWorking = working; }
    public PathPlanningContext getPathPlanningContext() { return pathPlanningContext; }
    public void setPathPlanningContext(PathPlanningContext pathPlanningContext) {
        this.pathPlanningContext = pathPlanningContext;
    }

    @Override
    public String toString() {
        return type + "[" + id + "], 位置: (" + positionX + ", " + positionY + "), " +
                "油量: " + fuel + "%, 状态: " + state.getStateName();
    }
}